package zb.blog.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import zb.blog.base.bean.Result;
import zb.blog.base.exception.ZbBlogException;
import zb.blog.base.global.GlobalVar;
import zb.blog.base.sessionScope.SessionScope;
import zb.blog.base.util.EmailUtil;
import zb.blog.base.util.EncryptUtil;
import zb.blog.bean.CommentBean;
import zb.blog.dao.CommentDao;
import zb.blog.dao.MessageDao;
import zb.blog.service.IMessageService;


import java.security.GeneralSecurityException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MessageService implements IMessageService {
    private static final Logger logger = LogManager.getLogger(ZbBlogException.class);
    @Autowired
    private MessageDao messageDao;


    @Override
    public PageInfo<CommentBean> getMessage(Map<String, String> param) {
        Integer pageNum = Integer.valueOf(param.get("pageNum"));
        Integer pageSize = Integer.valueOf(param.get("pageSize"));
        PageHelper.startPage(pageNum, pageSize);
        List<CommentBean> list = messageDao.getMessage(param);
        PageInfo<CommentBean> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public Result auditMessage(Integer status, Integer commentId, Integer isSendEmail, String content) throws GeneralSecurityException {
        Result r = new Result();
        if (status == null || commentId == null || isSendEmail == null) {
            r.setSuccess(GlobalVar.FAIL);
            r.setMsg("参数错误，审核失败！");
            return r;
        }
        if (isSendEmail == 1) {
            if (content == null || content.length() < -0) {
                r.setSuccess(GlobalVar.FAIL);
                r.setMsg("发送邮件必包含写发送内容！");
                return r;
            }
        }
        //根据comentId查询一些信息，用于发送邮件
        Integer auditorId = SessionScope.getLoginAuth().getUser().getId();
        Map<String, Object> map = messageDao.getMsgToEmailByCommtId(commentId);
        if (map == null || map.size() <= 0) {
            r.setSuccess(GlobalVar.FAIL);
            r.setMsg("找不到当前评论或留言！");
            return r;
        }
        int count = messageDao.updateComStatusByCommtId(commentId, status, auditorId);//更新状态
        if (count >= 1) {
            r.setSuccess(GlobalVar.SUCCESS);
            r.setMsg("审核成功！");
        } else {
            r.setSuccess(GlobalVar.FAIL);
            r.setMsg("审核失败！");
            return r;
        }
        //如果有回复信息就添加
        if (content != null && content.length() > 0) {
            int userId = SessionScope.getLoginAuth().getUser().getId();
            String artTitle = (String) map.get("article_title");
            Integer artId = (Integer) map.get("artId");
            CommentBean comtBean = new CommentBean();
            comtBean.setParent_Id(commentId);
            comtBean.setBlog_article_id(artId);
            comtBean.setUser_id(userId);
            comtBean.setArt_title(artTitle);
            comtBean.setAudit_status(status);
            comtBean.setAuditor_id(userId);
            comtBean.setBrowser("");
            comtBean.setContent(content);
            comtBean.setAudit_time("001");//设置为非null和非空即可
            comtBean.setAddress(SessionScope.getLoginAuth().getAddress());
            comtBean.setEmail(GlobalVar.EMAIL_ADDR);
            comtBean.setHeader_img(GlobalVar.QNY_FAVORITE_ICON);
            comtBean.setNickname(GlobalVar.NICKNAME);
            messageDao.addComment(comtBean);
            r.setSuccess(GlobalVar.SUCCESS);
            r.setMsg("审核成功！");

            if (isSendEmail == 1) {//发送邮件
                //通过HTML文档发送内容
                Integer type = (Integer) map.get("type");//1:关于我，2：留言，3：文章
                Map<String, String> param = new HashMap<>();
                param.put("type", String.valueOf(type));
                param.put("comm_time", (String) map.get("create_time"));
                param.put("reply_content", content);
                param.put("visitor_content", (String) map.get("visitor_content"));
                param.put("article_url", GlobalVar.DETAIL_PAGE_URL + "?id=" + EncryptUtil.customEncrypt(artId));
                param.put("article_title", (String) map.get("article_title"));
                param.put("audit_status", status == 1 ? "审核通过" : "审核不通过");

                Result res = EmailUtil.getEmailHtml(param);
                boolean isSendSuccess = false;
                if (res.getSuccess()) {
                    logger.info("正在发送邮件....");
                    isSendSuccess = EmailUtil.sendMail(new String[]{(String) map.get("email")}, GlobalVar.NICKNAME + "回复您", (String) res.getData());
                } else {
                    logger.info(res.getMsg());
                }
                if (isSendSuccess) {
                    r.setSuccess(GlobalVar.SUCCESS);
                    r.setMsg("发送邮件成功！");
                    logger.info("发送邮件成功!!!");
                } else {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    r.setSuccess(GlobalVar.FAIL);
                    r.setMsg("发送邮件失败！");
                    logger.info("发送邮件失败，事务回滚!!!");
                }
            }
        }
        return r;
    }
}
